package n2_common_methods;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * interrupt() 唤醒线程 抛异常：java.lang.InterruptedException: sleep interrupted
 *
 * private class : 使用 TimeUnit.SECONDS.sleep() 代替 Thread.sleep() 更直观
 */
@Slf4j(topic = "c.")
public class T3_interrupt {

    public static void main(String[] args) throws InterruptedException {
        final Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("[t1线程]-- 开始休眠 20秒......");

                try {
                    TimeUnit.SECONDS.sleep(20);
                } catch (InterruptedException e) {
                    log.debug("[t1线程]--已经被唤醒  ......");
                    e.printStackTrace();
                }

            }
        };
        t1.start();

        TimeUnit.SECONDS.sleep(1); // 主线程 休眠
        log.debug("main主线程 休眠一秒后 唤醒t1线程：interrupt...");
        t1.interrupt();

        /*
        10:20:41.090 [t1] c. - [t1线程]-- 开始休眠 20秒......
        10:20:42.088 [main] c. - main主线程 休眠一秒后 唤醒t1线程：interrupt...
        10:20:42.088 [t1] c. - [t1线程]--已经被唤醒  ......
        java.lang.InterruptedException: sleep interrupted
            at java.lang.Thread.sleep(Native Method)
            at n2_common_methods.T3_interrupt$1.run(T3_interrupt.java:22)

        */
    }

    /**
     * 使用 TimeUnit.SECONDS.sleep() 代替 Thread.sleep() 更直观
     */
    public static class Test_TimeUtils{
        public static void main(String[] args) throws InterruptedException {

            log.debug("enter..");
            TimeUnit.SECONDS.sleep(1);
            log.debug("end..");
        }
    }

}
